/// <reference path="../Bootstrap/js/bootstrap.min.js" />
/// <reference path="../Knockout/knockout.mapping-latest.js" />
/// <reference path="../Knockout/knockout-3.3.0.js" />
/// <reference path="mars.validation.js" />
/// <reference path="jquery-1.11.2.min.js" />
/// <reference path="mars.docmgnt.js" />
/// <reference path="sp.listmgnt.js" />
/// <reference path="mars.masterlists.js" />
/// <reference path="mars.utility.js" />0
/// <reference path="mars.constants.js" />
/// <reference path="mars.min.js" />
/// <reference path="../JQueryValidation/jquery.validate.min.js" />

var ViewModel = function (data) {
    var self = this;
    self.ModelCheckOutModel = new ModelCheckOutModel(data);
    self.ModelSummaryModel = new ModelSummaryModel(data);
    self.ValidationHomeModel = new ValidationHomeModel(data);
    self.ModelRiskScoreModel = new ModelRiskScoreModel(data);    
    self.KeyFindingsModel = new KeyFindingsModel(data);

    self.AcknowledgementDocumentModel = new AcknowledgementDocumentModel(data);

    self.ShowValidationHomeTab = ko.computed(function () {
        if (data.ValidationStatus != MARS_CONSTANTS.VALIDATION_STATUS.NEW) {
            return true;
        }
        return false;
    }, this);

    self.ShowModelRiskScoreTab = ko.computed(function () {
        if (data.ValidationStatus != MARS_CONSTANTS.VALIDATION_STATUS.NEW) {
            return true;
        }
        return false;
    }, this);

    self.ShowKeyFindingsTab = ko.computed(function () {
        if (data.ValidationStatus != MARS_CONSTANTS.VALIDATION_STATUS.NEW) {
            return true;
        }
        return false;
    }, this);

    self.ShowAcknowledgementDocTab = ko.computed(function () {
        if (data.ValidationStatus != MARS_CONSTANTS.VALIDATION_STATUS.NEW) {
            return true;
        }
        return false;
    }, this);
}

var ModelCheckOutModel = function (data) {
    var self = this;
    self.ValidationId = ko.observable(data.ValidationId);
    self.CheckedOutToName = ko.observable(data.CheckedOutToName);
    self.CheckedOutToUserName = ko.observable(data.CheckedOutToUserName);
    self.CheckedOutToEmail = ko.observable(data.CheckedOutToEmail);

    self.IsModelCheckedOut = ko.computed(function () {
        if (self.CheckedOutToName() != null && self.CheckedOutToName() != ""
            && self.CheckedOutToName() != undefined) {
            return true;
        }
        return false;
    }, this);

    self.IsModelCheckedOutToMe = ko.computed(function () {
        var cu = MarsUtility.GetCurrentUser();
        if (cu != null && self.IsModelCheckedOut() && self.CheckedOutToUserName() == cu.LoginName) {
            return true;
        }
        return false;
    }, this);

    self.JSObject = ko.computed(function () {
        return ko.mapping.toJS(self, MARS_CONSTANTS.IGNORE_MAPPING_CHECKOUT_MODEL);;
    }, this);

    self.CheckOutModel = function () {
        var oldCheckedOutToName = self.CheckedOutToName();
        var oldCheckOutToUserName = self.CheckedOutToUserName();
        var oldCheckOutToEmail = self.CheckedOutToEmail();
        var cu = MarsUtility.GetCurrentUser();
        self.CheckedOutToName(cu.Title);
        self.CheckedOutToUserName(cu.LoginName);
        self.CheckedOutToEmail(cu.Email);
        if (MarsUtility.SubmitModelChanges(self.JSObject())) {
            BootstrapDialog.alert("Model is checked out to you now!");
        }
        else {
            self.CheckedOutToName(oldCheckedOutToName);
            self.CheckedOutToUserName(oldCheckOutToUserName);
            self.CheckedOutToEmail(oldCheckOutToEmail);
        }
    };

    self.CheckInModel = function () {
        var metadata = self.JSObject();
        metadata.CheckedOutToName = "";
        metadata.CheckedOutToUserName = "";
        metadata.CheckedOutToEmail = "";
        if (MarsUtility.SubmitModelChanges(metadata)) {
            self.CheckedOutToName("");
            self.CheckedOutToUserName("");
            self.CheckedOutToEmail("");
            BootstrapDialog.alert("Model Checked In Successfully.");
        }
    };
}

var ModelSummaryModel = function (data) {
    var self = this;
    self.Title = data.ValidationId;
    self.ModelId = data.ModelId;
    self.ValidationId = data.ValidationId;
    self.ModelSubmitter = ko.observable(data.ModelSubmitter);
    self.ModelName = ko.observable(data.ModelName);
    self.DevelopmentSource = ko.observable(data.DevelopmentSource);
    self.ModelDescription = ko.observable(data.ModelDescription);
    self.VendorPlatform = ko.observable(data.VendorPlatform);
    self.ProductionSystem = ko.observable(data.ProductionSystem);
    self.TargetSubmissionDate = ko.observable(data.TargetSubmissionDate);
    self.ModelActiveByDate = ko.observable(MarsUtility.GetFormattedDate(data.ModelActiveByDate));
    self.PlatformOrSystemId = ko.observable(data.PlatformOrSystemId);
    self.ScopeSubmitted = ko.observable(data.ScopeSubmitted);
    self.BusinessUnit = ko.observable(data.BusinessUnit);
    self.IVGHead = ko.observable(data.IVGHead);
    self.ModelOwner = ko.observable(data.ModelOwner);
    self.BusinessUnitExecutive = ko.observable(data.BusinessUnitExecutive);
    self.StreamLead = ko.observable(data.StreamLead);
    self.MRO = ko.observable(data.MRO);
    self.ModelStatus = ko.observable(data.ModelStatus);
    self.ValidationStatus = ko.observable(data.ValidationStatus);

    self.RiskAcceptanceCommitteeNameList = ko.observableArray(MasterListsUtility.GetConfigValueArray("RiskAcceptanceCommitteeNames"));
    self.RiskAcceptanceCommitteeName = ko.observable(data.RiskAcceptanceCommitteeName),
    self.RiskAcceptanceStartDate = ko.observable(data.RiskAcceptanceStartDate),
    self.RiskAcceptanceEndDate = ko.observable(data.RiskAcceptanceEndDate),
    self.RiskAcceptanceClosingDate = ko.observable(data.RiskAcceptanceClosingDate),

    self.Tier1UseCases = ko.observable(data.Tier1UseCases);
    self.Tier2UseCases = ko.observable(data.Tier2UseCases);
    self.Tier3UseCases = ko.observable(data.Tier3UseCases);
    self.Tier4UseCases = ko.observable(data.Tier4UseCases);

    self.CheckedTier1UseCases = ko.observableArray(self.Tier1UseCases() != null ? self.Tier1UseCases().split(",") : "");
    self.CheckedTier2UseCases = ko.observableArray(self.Tier2UseCases() != null ? self.Tier2UseCases().split(",") : "");
    self.CheckedTier3UseCases = ko.observableArray(self.Tier3UseCases() != null ? self.Tier3UseCases().split(",") : "");
    self.CheckedTier4UseCases = ko.observableArray(self.Tier4UseCases() != null ? self.Tier4UseCases().split(",") : "");

    self.Tier1UseCasesList = ko.observableArray(MasterListsUtility.GetConfigValueArray("Tier1UseCases"));
    self.Tier2UseCasesList = ko.observableArray(MasterListsUtility.GetConfigValueArray("Tier2UseCases"));
    self.Tier3UseCasesList = ko.observableArray(MasterListsUtility.GetConfigValueArray("Tier3UseCases"));
    self.Tier4UseCasesList = ko.observableArray(MasterListsUtility.GetConfigValueArray("Tier4UseCases"));

    self.DevelopmentSourceList = ko.observableArray(MasterListsUtility.GetConfigValueArray("DevelopmentSource"));
    self.BusinessUnitList = ko.observableArray(data.ModelSubmitter != null && data.ModelSubmitter != "" ? MasterListsUtility.GetBUList(data.ModelSubmitter) : []);
    self.IVGHeadList = ko.observableArray(MasterListsUtility.GetIVGHeadList());
    self.ModelOwnerList = ko.observableArray((data.ModelSubmitter != null && data.ModelSubmitter != "") ? MasterListsUtility.GetModelOwnerList(data.ModelSubmitter) : []);
    self.BusinessUnitExecutiveList = ko.observableArray(MasterListsUtility.GetBUEList());
    self.StreamLeadList = ko.observableArray(MasterListsUtility.GetStreamLeadList());
    self.MROList = ko.observableArray(MasterListsUtility.GetMROList());

    this.IsNewModel = ko.computed(function () {
        if (self.ValidationStatus() == MARS_CONSTANTS.VALIDATION_STATUS.NEW) {
            return true;
        }
        return false;
    }, this);

    self.JSObject = ko.computed(function () {
        return ko.mapping.toJS(self, MARS_CONSTANTS.IGNORE_MAPPING_MODEL_SUMMARY);;
    }, this);

    self.SubmitModel = function () {
        self.Tier1UseCases(self.CheckedTier1UseCases().join());
        self.Tier2UseCases(self.CheckedTier2UseCases().join());
        self.Tier3UseCases(self.CheckedTier3UseCases().join());
        self.Tier4UseCases(self.CheckedTier4UseCases().join());
        if(MarsUtility.SubmitModelInfo($.extend(self.JSObject(), modelData.ValidationHomeModel.JSObject(),
            modelData.ModelRiskScoreModel.JSObject(), modelData.KeyFindingsModel.JSObject(), 
            modelData.AcknowledgementDocumentModel.JSObject(),
            modelData.ModelCheckOutModel.JSObject()))) {
            BootstrapDialog.alert("Model Submitted Successfully.");
            window.location = _spPageContextInfo.webAbsoluteUrl;
        }
        else {
            //BootstrapDialog.alert("Model Submitted Successfully.");
        }
    };

    self.SaveModelChanges = function () {
        self.Tier1UseCases(self.CheckedTier1UseCases().join());
        self.Tier2UseCases(self.CheckedTier2UseCases().join());
        self.Tier3UseCases(self.CheckedTier3UseCases().join());
        self.Tier4UseCases(self.CheckedTier4UseCases().join());

        if (MarsUtility.SubmitModelChanges(self.JSObject())) {
            BootstrapDialog.alert("Model Saved Successfully.");
        }
    }
}

var ValidationHomeModel = function (data) {
    var self = this;
    self.ValidationId = ko.observable(data.ValidationId)
    self.LeadValidator = ko.observable(data.LeadValidator);
    self.ValidationTracker = ko.observable(data.ValidationTracker);
    self.Phase1Progress = ko.observable(data.Phase1Progress);
    self.Phase2Progress = ko.observable(data.Phase2Progress);
    self.Phase3Progress = ko.observable(data.Phase3Progress);
    self.Phase4Progress = ko.observable(data.Phase4Progress);
    self.Phase5Progress = ko.observable(data.Phase5Progress);
    self.Phase6Progress = ko.observable(data.Phase6Progress);

    self.ChatHistoryModel = new ChatHistoryModel(data);

    self.DevelopmentDocuments = ko.observableArray(MarsUtility.GetMarsDocuments(data.ValidationId, MARS_CONSTANTS.FOLDER_NAMES.DEVELOPMENT_DOCUMENTS)),
    self.UploadDevelopmentDocuments = function () {
        DocUtility.UploadFile("Upload Development Document",
            MARS_CONSTANTS.MARS_LIST_NAMES.MARS_DOCUMENTS + "/" + self.ValidationId() + "/" + MARS_CONSTANTS.FOLDER_NAMES.DEVELOPMENT_DOCUMENTS,
            function () { self.DevelopmentDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.DEVELOPMENT_DOCUMENTS)); });
    };

    self.ImplementationDocuments = ko.observableArray(MarsUtility.GetMarsDocuments(data.ValidationId, MARS_CONSTANTS.FOLDER_NAMES.IMPLEMENTATION_DOCUMENTS)),
    self.UploadImplementationDocuments = function () {
        DocUtility.UploadFile("Upload Implementation Document",
            MARS_CONSTANTS.MARS_LIST_NAMES.MARS_DOCUMENTS + "/" + self.ValidationId() + "/" + MARS_CONSTANTS.FOLDER_NAMES.IMPLEMENTATION_DOCUMENTS,
            function () { self.ImplementationDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.IMPLEMENTATION_DOCUMENTS)); });
    };

    self.IndependentValidationDocuments = ko.observableArray(MarsUtility.GetMarsDocuments(data.ValidationId, MARS_CONSTANTS.FOLDER_NAMES.INDEPENDENT_VALIDATION_DOCUMENTS)),
    self.UploadIndependentValidationDocuments = function () {
        DocUtility.UploadFile("Upload Independent Validation Document",
            MARS_CONSTANTS.MARS_LIST_NAMES.MARS_DOCUMENTS + "/" + self.ValidationId() + "/" + MARS_CONSTANTS.FOLDER_NAMES.INDEPENDENT_VALIDATION_DOCUMENTS,
            function () { self.IndependentValidationDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.INDEPENDENT_VALIDATION_DOCUMENTS)); });
    };

    self.ExecutiveSummaryDocuments = ko.observableArray(MarsUtility.GetMarsDocuments(data.ValidationId, MARS_CONSTANTS.FOLDER_NAMES.EXECUTIVE_SUMMARY)),
    self.UploadExecutiveSummaryDocuments = function () {
        DocUtility.UploadFile("Upload Executive Summary Document",
            MARS_CONSTANTS.MARS_LIST_NAMES.MARS_DOCUMENTS + "/" + self.ValidationId() + "/" + MARS_CONSTANTS.FOLDER_NAMES.EXECUTIVE_SUMMARY,
            function () { self.ExecutiveSummaryDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.EXECUTIVE_SUMMARY)); });
    };

    self.DataSetDocuments = ko.observableArray(MarsUtility.GetMarsDocuments(data.ValidationId, MARS_CONSTANTS.FOLDER_NAMES.DATA_SET));
    self.UploadDataSetDocuments = function () {
        DocUtility.UploadFile("Upload Data Set Document",
            MARS_CONSTANTS.MARS_LIST_NAMES.MARS_DOCUMENTS + "/" + self.ValidationId() + "/" + MARS_CONSTANTS.FOLDER_NAMES.DATA_SET,
            function () { self.DataSetDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.DATA_SET)); });
    };

    self.AncillaryDocuments = ko.observableArray(MarsUtility.GetMarsDocuments(data.ValidationId, MARS_CONSTANTS.FOLDER_NAMES.ANCILLARY_DOCUMENTS));
    self.UploadAncillaryDocuments = function () {
        DocUtility.UploadFile("Upload Ancillary Document",
            MARS_CONSTANTS.MARS_LIST_NAMES.MARS_DOCUMENTS + "/" + self.ValidationId() + "/" + MARS_CONSTANTS.FOLDER_NAMES.ANCILLARY_DOCUMENTS,
            function () { self.AncillaryDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.ANCILLARY_DOCUMENTS)); });
    };

    self.LeadValidatorList = ko.observableArray(MasterListsUtility.GetLeadValidatorList());
    self.ValidationTrackerList = ko.observableArray(MasterListsUtility.GetValidationTrackerList());

    self.Phase1ProgressList = ko.observableArray(MasterListsUtility.GetPhase1ProgressList());
    self.Phase2ProgressList = ko.observableArray(MasterListsUtility.GetProgressList());
    self.Phase3ProgressList = ko.observableArray(MasterListsUtility.GetProgressList());
    self.Phase4ProgressList = ko.observableArray(MasterListsUtility.GetProgressList());
    self.Phase5ProgressList = ko.observableArray(MasterListsUtility.GetProgressList());
    self.Phase6ProgressList = ko.observableArray(MasterListsUtility.GetProgressList());

    self.JSObject = ko.computed(function () {
        return ko.mapping.toJS(self, MARS_CONSTANTS.IGNORE_MAPPING_VALIDATION_HOME);;
    }, this);
       
    self.DeleteDocument = function(document) {
        if (confirm("Are you sure you want to delete " + document.Name + "?")) {
            if (DocUtility.DeleteDocument(document.ServerRelativeUrl)) {
                self.DevelopmentDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.DEVELOPMENT_DOCUMENTS));
                self.ImplementationDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.IMPLEMENTATION_DOCUMENTS));
                self.IndependentValidationDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.INDEPENDENT_VALIDATION_DOCUMENTS));
                self.ExecutiveSummaryDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.EXECUTIVE_SUMMARY));
                self.DataSetDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.DATA_SET));
                self.AncillaryDocuments(MarsUtility.GetMarsDocuments(self.ValidationId(), MARS_CONSTANTS.FOLDER_NAMES.ANCILLARY_DOCUMENTS));
            }
            else {
                alert("Error: could not delete the document. Please contact administrator");
            }
        }
    }

    self.SaveModelChanges = function () {
        if (MarsUtility.SubmitModelChanges(self.JSObject())) {
            BootstrapDialog.alert("Model Saved Succesfully.");
        }
    }
}

var ChatHistoryModel = function (data) {
    var self = this;
    self.ValidationId = ko.observable(data.ValidationId);
    self.ChatMessage = ko.observable("");
    var currentUser = data.CurrentUser;
    self.ChatUserUserName = ko.observable(currentUser != null ? currentUser.LoginName : "");
    self.ChatUserFullName = ko.observable(currentUser != null ? currentUser.Title : "");
    self.ChatDateTime = ko.observable("");

    self.ChatMessages = ko.observable("");
    self.ChatUserUserNames = ko.observable("");
    self.ChatUserFullNames = ko.observable("");
    self.ChatDateTimes = ko.observable("");

    self.ChatMessageList = data.ChatMessages != null ? data.ChatMessages.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
    self.ChatUserUserNameList = data.ChatUserUserNames != null ? data.ChatUserUserNames.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
    self.ChatUserFullNameList = data.ChatUserFullNames != null ? data.ChatUserFullNames.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
    self.ChatDateTimeList = data.ChatDateTimes != null ? data.ChatDateTimes.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];

    self.GetChatHistory = function () {
        var chatHistory = [];
        for (var i = 0; i < self.ChatMessageList.length; i++) {
            chatHistory.push({
                ChatMessage: self.ChatMessageList[i],
                ChatUserUserName: self.ChatUserUserNameList[i],
                ChatUserFullName: self.ChatUserFullNameList[i],
                ChatDateTime: self.ChatDateTimeList[i],
            });
        }
        return chatHistory;
    }

    self.ChatHistory = ko.observableArray(self.GetChatHistory());
    
    self.EnableAddMessageButton = ko.computed(function () {
        var enable = false;
        if (self.ChatMessage() != null && self.ChatMessage() != undefined && self.ChatMessage() != "") {
            enable = true;
        }
        return enable;
    }, this);

    self.AddCommentMessage = function () {
        self.UpdateChatHistory();
        if (self.ChatMessage() != "" && self.ChatMessage() != null && self.ChatMessage() != undefined) {
            self.ChatDateTime(MarsUtility.GetCurrentDateTime());

            self.ChatMessageList.push(self.ChatMessage());
            self.ChatUserUserNameList.push(self.ChatUserUserName());
            self.ChatUserFullNameList.push(self.ChatUserFullName());
            self.ChatDateTimeList.push(self.ChatDateTime());

            self.ChatMessages(self.ChatMessageList.join(MARS_CONSTANTS.STRING_SEPERATOR));
            self.ChatUserUserNames(self.ChatUserUserNameList.join(MARS_CONSTANTS.STRING_SEPERATOR));
            self.ChatUserFullNames(self.ChatUserFullNameList.join(MARS_CONSTANTS.STRING_SEPERATOR));
            self.ChatDateTimes(self.ChatDateTimeList.join(MARS_CONSTANTS.STRING_SEPERATOR));

            if (MarsUtility.SubmitModelChanges(self.JSObject())) {
                self.ChatHistory.push(
                {
                    ChatMessage: self.ChatMessage(),
                    ChatUserUserName: self.ChatUserUserName(),
                    ChatUserFullName: self.ChatUserFullName(),
                    ChatDateTime: self.ChatDateTime(),
                });
            }
            else {
                self.ChatMessageList.pop();
                self.ChatUserUserNameList.pop();
                self.ChatUserFullNameList.pop();
                self.ChatDateTimeList.pop();
                alert("Error: could not add message. Please contact administrator.");
            }
            self.ChatMessage("");
        }        
    }

    self.JSObject = function () {
        return ko.mapping.toJS(self, MARS_CONSTANTS.IGNORE_MAPPING_CHAT_HISTORY_MODEL);;
    }

    self.UpdateChatHistory = function() {
        try {
            //setInterval(function () {
            //    var data = ListUtility.GetSingleListItem(_spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('" + MARS_CONSTANTS.MARS_LIST_NAMES.MARS_MAIN + "')/items?$filter=(ValidationId eq '" + self.ValidationId() + "')");
            //    self.ChatMessageList = data.ChatMessages != null ? data.ChatMessages.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
            //    self.ChatUserUserNameList = data.ChatUserUserNames != null ? data.ChatUserUserNames.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
            //    self.ChatUserFullNameList = data.ChatUserFullNames != null ? data.ChatUserFullNames.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
            //    self.ChatDateTimeList = data.ChatDateTimes != null ? data.ChatDateTimes.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
            //    self.ChatHistory(self.GetChatHistory());
            //}, 5000);            
        } catch (e) {
            console.log(e);
            // Ignore exception.
        }
    }

    self.UpdateChatHistory();
}

var KeyFindingsModel = function (data) {
    var self = this;
    self.ValidationId = ko.observable(data.ValidationId);

    self.FindingNumbers = ko.observable(data.FindingNumbers != null ? data.FindingNumbers : "");
    self.FindingTypes = ko.observable(data.FindingTypes != null ? data.FindingTypes : "");
    self.FindingDescriptions = ko.observable(data.FindingDescriptions != null ? data.FindingDescriptions : "");
    self.ActionPlans = ko.observable(data.ActionPlans != null ? data.ActionPlans : "");
    self.TargetDates = ko.observable(data.TargetDates != null ? data.TargetDates : "");
    self.CompletionDates = ko.observable(data.CompletionDates != null ? data.CompletionDates : "");

    self.FindingTypesList = data.FindingTypes != null ? data.FindingTypes.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
    self.FindingNumbersList = data.FindingNumbers != null ? data.FindingNumbers.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
    self.FindingDescriptionsList = data.FindingDescriptions != null ? data.FindingDescriptions.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
    self.ActionPlansList = data.ActionPlans != null ? data.ActionPlans.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
    self.TargetDatesList = data.TargetDates != null ? data.TargetDates.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];
    self.CompletionDatesList = data.CompletionDates != null ? data.CompletionDates.split(MARS_CONSTANTS.STRING_SEPERATOR) : [];

    self.FindingType = ko.observable("");
    self.FindingDescription = ko.observable("");
    self.ActionPlan = ko.observable("");
    self.TargetDate = ko.observable("");
    self.CompletionDate = ko.observable("");

    self.FindingTypeList = ko.observableArray(MasterListsUtility.GetFindingTypeList());
    
    self.JSObject = ko.computed(function () {
        return ko.mapping.toJS(self, MARS_CONSTANTS.IGNORE_MAPPING_KEY_FINDINGS);
    }, this);

    self.GetKeyFindings = function () {
        var kfs = [];
        for (var i = 0; i < self.FindingTypesList.length; i++) {
            kfs.push({
                FindingNumber: self.FindingNumbersList[i],
                FindingType: self.FindingTypesList[i],
                FindingDescription: self.FindingDescriptionsList[i],
                ActionPlan: self.ActionPlansList[i],
                TargetDate: self.TargetDatesList[i],
                CompletionDate: self.CompletionDatesList[i]
            });
        }
        return kfs;
    };

    self.KeyFindings = ko.observableArray(self.GetKeyFindings());

    self.FindingNumber = ko.computed(function () {
        return self.ValidationId() + "_" + self.FindingType() + "_" + (self.KeyFindings().length + 1)
    }, this);

    self.EnableSaveChangesButton = ko.computed(function() {
        //var enable = false;        
        //var userRole = MarsUtility.GetUserRole(data.CurrentUser.LoginName);
        //if(userRole != null && (userRole.Role == MARS_CONSTANTS.USER_ROLES.ADMIN || userRole.Role == MARS_CONSTANTS.USER_ROLES.IVG
        //    || userRole.Role == MARS_CONSTANTS.USER_ROLES.IVG_HEAD || userRole.Role == MARS_CONSTANTS.USER_ROLES.STREAM_LEAD
        //    || userRole.Role == MARS_CONSTANTS.USER_ROLES.MODEL_OWNER || userRole.Role == MARS_CONSTANTS.USER_ROLES.MODEL_SUBMITTER
        //    || userRole.Role == MARS_CONSTANTS.USER_ROLES.MRO_CRO)) {
        //    enable = true;
        //}
        //return enable;
        return true;
    }, this)

    self.AddKeyFinding = function () {
        self.FindingNumbersList.push(self.FindingNumber());
        self.FindingTypesList.push(self.FindingType());
        self.FindingDescriptionsList.push(self.FindingDescription());
        self.ActionPlansList.push(self.ActionPlan());
        self.TargetDatesList.push(self.TargetDate());
        self.CompletionDatesList.push(self.CompletionDate());

        self.KeyFindings.push({
            FindingNumber: self.FindingNumber(),
            FindingType: self.FindingType(),
            FindingDescription: self.FindingDescription(),
            ActionPlan: self.ActionPlan(),
            TargetDate: self.TargetDate(),
            CompletionDate: self.CompletionDate()
        });
        self.CloseKeyFindingForm();
    };

    self.ResetKeyFindingForm = function () {
        self.FindingType("");
        self.FindingDescription("");
        self.ActionPlan("");
        self.TargetDate("");
        self.CompletionDate("");
    };

    self.CloseKeyFindingForm = function () {
        self.ResetKeyFindingForm();
        $('#AddKeyFindingForm').modal('hide');
    };

    self.EditKeyFinding = function () {
        $('#AddKeyFindingForm').modal('show');
        //FindingDescription: this.FindingDescription;
    };

    self.SaveModelChanges = function () {
        self.FindingNumbers(self.FindingNumbersList.join(MARS_CONSTANTS.STRING_SEPERATOR));
        self.FindingTypes(self.FindingTypesList.join(MARS_CONSTANTS.STRING_SEPERATOR));
        self.FindingDescriptions(self.FindingDescriptionsList.join(MARS_CONSTANTS.STRING_SEPERATOR));
        self.ActionPlans(self.ActionPlansList.join(MARS_CONSTANTS.STRING_SEPERATOR));
        self.TargetDates(self.TargetDatesList.join(MARS_CONSTANTS.STRING_SEPERATOR));
        self.CompletionDates(self.CompletionDatesList.join(MARS_CONSTANTS.STRING_SEPERATOR));
        if (MarsUtility.SubmitModelChanges(self.JSObject())) {
            BootstrapDialog.alert("Model Saved Succesfully.");
        }
    };
}

var ModelRiskScoreModel = function (data) {
    var self = this;
    self.ValidationId = ko.observable(data.ValidationId);
    self.CurrentUserName = ko.observable(data.CurrentUserName);
    self.AsOfDate = ko.observable(data.AsOfDate);
    self.RiskFile = ko.observable(data.RiskFile);
    self.IntrinsicModelQuality = ko.observable(data.IntrinsicModelQuality);
    self.RiskMitigationIndex = ko.observable(data.RiskMitigationIndex);
    self.RMIWithDataPenalty = ko.observable(data.RMIWithDataPenalty);
    self.ModelQualityScore = ko.observable(data.ModelQualityScore);
    self.Exposure = ko.observable(data.Exposure);
    self.ModelRiskScore = ko.observable(data.ModelRiskScore);
    self.ExposureComments = ko.observable(data.ExposureComments);

    self.JSObject = ko.computed(function () {
        return ko.mapping.toJS(self, MARS_CONSTANTS.IGNORE_MAPPING_MODEL_RISK_SCORE);
    }, this);

    self.IMQ_A_QUESTIONAIRE = ko.observableArray(MRS_QUESTIONAIRE.IMQ_A_QUESTIONAIRE);
    //self.IMQ_B_QUESTIONAIRE = ko.observable(data.IMQ_A_QUESTIONAIRE);
    //self.IMQ_C_QUESTIONAIRE = ko.observable(data.IMQ_A_QUESTIONAIRE);
    //self.IMQ_D_QUESTIONAIRE = ko.observable(data.IMQ_A_QUESTIONAIRE);

}

var AcknowledgementDocumentModel = function (data) {
    var self = this;
    self.ValidationId = ko.observable(data.ValidationId);
    self.ValidatedFor = ko.observable(data.ValidatedFor);
    self.ValidationScope = ko.observable(data.ValidationScope);
    self.ValidationStatement = ko.observable(data.ValidationStatement);
    self.IVGApprovalExpiryDate = ko.observable(data.IVGApprovalExpiryDate);
    self.AcknowledgementDate = ko.observable(data.AcknowledgementDate);

    self.JSObject = ko.computed(function () {
        return ko.mapping.toJS(self, MARS_CONSTANTS.IGNORE_MAPPING_ACKNOWLEDGEMENT_DOCUMENT);
    }, this);

    self.SaveModelChanges = function () {
        if (MarsUtility.SubmitModelChanges(self.JSObject())) {
            BootstrapDialog.alert("Model Saved Successfully.");
        }
    }

    self.PassToIVG = function () {
        if (MarsUtility.SubmitModelChanges(self.JSObject())) {
            BootstrapDialog.alert("Model Saved Successfully.");
        }
    }
}

function GetDefaultChatHistory() {
    var array = [];
    array.push({ ChatMessage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.", ChatUserUserName: "investments\ankith", ChatUserFullName: "Ankith Nanagiri", ChatDateTime: "Fri, 1 May 2015 14:36:08 UTC" });
    array.push({ ChatMessage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.", ChatUserUserName: "investments\narendra", ChatUserFullName: "Narendra patil", ChatDateTime: "Fri, 1 May 2015 14:36:08 UTC" });
    array.push({ ChatMessage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.", ChatUserUserName: "investments\suhas", ChatUserFullName: "Suhas Pise", ChatDateTime: "Fri, 1 May 2015 14:36:08 UTC" });
    array.push({ ChatMessage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.", ChatUserUserName: "investments\avinash", ChatUserFullName: "Avinash", ChatDateTime: "Fri, 1 May 2015 14:36:08 UTC" });
    array.push({ ChatMessage: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.", ChatUserUserName: "investments\rahul", ChatUserFullName: "Rahul Babar", ChatDateTime: "Fri, 1 May 2015 14:36:08 UTC" });
    return array;
}

